package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        // 创建队列
        c.queueDeclare("helloworld", false, false, false, null);


        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到： "+s);
                //  模拟处理耗时消息
                //  遍历字符串找 '.' 字符，每找到一个都暂停1秒
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == '.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                System.out.println("---------------------消息处理结束");

            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        // 从 helloworld 接收消息
        /*
        第二个参数 true： 自动确认、自动 ACK(Acknowledgement)
         */
        c.basicConsume("helloworld", true, deliverCallback, cancelCallback);
    }
}
